<?php

error_reporting(E_ALL);
$service_port = 5581; //这里是端口号
$address = 'chengnankeji.tpddns.cn';//这里输入服务器端IP地址
//↓创建 TCP/IP socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket < 0) {
    echo "socket创建失败原因: " . socket_strerror($socket) . "</br>";
} else {
    echo "socket创建成功.</br>"; //socket创建成功
}
$result = socket_connect($socket, $address, $service_port);
if ($result < 0) {
    echo "SOCKET连接失败原因: ($result) " . socket_strerror($result) . "</br>";
} else {
    echo "SOCKET连接成功.</br>"; //socket连接成功
}
//发送命令
$sendStr = "7E 00 01 05 00 06 0D";//发送内容
echo "发送：".$sendStr."<br>";
$sendStrArray = str_split(str_replace(' ', '', $sendStr), 2);  // 将16进制数据转换成两个一组的数组
$str = '';
for ($j = 0; $j < count($sendStrArray); $j++) {
    socket_write($socket, chr(hexdec($sendStrArray[$j])));  // 逐组数据发送
}
$receiveStr = "";
$receiveStr = socket_read($socket, 1024, PHP_BINARY_READ);  // 采用2进制方式接收数据
$receiveStrHex = bin2hex($receiveStr);  // 将2进制数据转换成16进制
echo implode(" ",str_split(str_replace(' ', '', $receiveStrHex), 2)) ;
socket_close($socket);  // 关闭Socket
